package com.cy.pj.sys.controller;

import com.cy.pj.common.pojo.JsonResult;
import com.cy.pj.common.pojo.PageObject;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user/")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("doUpdateObject")
    public JsonResult doUpdateObject(SysUser entity,Integer[] roleIds){
        sysUserService.updateObject(entity,roleIds);
        return new JsonResult("update ok");
    }

    @GetMapping("doFindById/{id}") //这里的url要与客户端一致
    public JsonResult doFindById(@PathVariable Integer id){
        return new JsonResult(sysUserService.findById(id));
    }

    @PostMapping("doSaveObject")
    public JsonResult doSaveObject(SysUser entity,Integer[] roleIds){
        sysUserService.saveObject(entity,roleIds);

        return new JsonResult("save ok");
    }

    @RequestMapping("doValidById/{id}/{valid}")
    public JsonResult doValidById(@PathVariable Integer id,
                                  @PathVariable Integer valid){
        sysUserService.validById(id,valid);
        return new JsonResult("update ok");
    }

    @GetMapping("doFindPageObjects")
    public JsonResult doFindPageObjects(String username,
                                        Integer pageCurrent){
        PageObject<SysUser> pageObject=
                sysUserService.findPageObjects(username,pageCurrent);
        return new JsonResult(pageObject);
    }
    @RequestMapping("doLogin")
    public JsonResult doLogin(String username,String password){
        //1.获取 Subject 对象
        Subject subject= SecurityUtils.getSubject();
        //2.通过 Subject 提交用户信息,交给 shiro 框架进行认证操作
        //2.1 对用户进行封装
        UsernamePasswordToken token=
                new UsernamePasswordToken(
                        username,//身份信息
                        password);//凭证信息
        //2.2 对用户信息进行身份认证
        subject.login(token);
        //分析:
        //1)token 会传给 shiro 的 SecurityManager
        //2)SecurityManager 将 token 传递给认证管理器
        //3)认证管理器会将 token 传递给 realm
        return new JsonResult("login ok");
    }
}
